package com.authapi.sample.api.utils;

import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.Random;

public class VerifyCodeUtils {
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    public static BufferedImage generateImage(String code) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();
        Random random = new Random();

        // 绘制背景色
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制干扰线
        for (int i = 0; i < 6; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(20);
            int y2 = random.nextInt(20);
            g2d.drawLine(x1, y1, x1 + x2, y1 + y2);
        }

        // 绘制验证码文本
        g2d.setFont(new Font("Arial", Font.BOLD, 20));
        for (int i = 0; i < code.length(); i++) {
            g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            int x = 10 + i * 20;
            int y = 25 + random.nextInt(10);
            g2d.drawString(code.charAt(i) + "", x, y);
        }

        g2d.dispose();
        return image;
    }
    public static String BufferedImageToBase64(BufferedImage bufferedImage) {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", bao);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = Base64.getEncoder().encode(bao.toByteArray());
        String base64 = new String(bytes);
        base64 = base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        return "data:image/png;base64," + base64;
    }



}
